<template>
  <div class="editor">
    <div style="border: 1px solid #ccc">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
      />
      <Editor
        style="height: 200px; overflow-y: hidden"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        @onCreated="handleCreated"
      />
    </div>
  </div>
</template>
<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { onBeforeUnmount, ref, shallowRef, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import type { IEditorConfig } from '@wangeditor/editor'

import { BASE_URL } from '@/service/config'
import useLoginStore from '@/store/login/login'

const props = defineProps<{
  modelValue: string
}>()
const emit = defineEmits(['update:modelValue'])
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
const loginStore = useLoginStore()
// 内容 HTML
const valueHtml = ref(props.modelValue)

const toolbarConfig = {}
const editorConfig: Partial<IEditorConfig> = { MENU_CONF: {} }
editorConfig.MENU_CONF!['uploadImage'] = {
  server: `${BASE_URL}/file/post/picture`,
  fieldName: 'post-picture',
  maxNumberOfFiles: 10,
  headers: {
    Authorization: loginStore.token
  },
  // 单个文件上传成功之后
  onSuccess(file: File, res: any) {
    console.log(`${file.name} 上传成功`, res)
  }
}

watch(valueHtml, (newValue) => {
  emit('update:modelValue', newValue)
})

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor: any) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

defineExpose({
  valueHtml
})
</script>

<style scoped lang="less">
.editor {
}
</style>
